package com.czl.module_storehouse.activity.inventory.scan;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.widget.PopupWindowCompat;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.util.SpHelper;
import com.czl.module_base.activity.BaseActivity;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.utils.ParcelHelper;
import com.czl.module_base.utils.PopWindowUtils;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.inventory.profit.InventoryProfitActivity;
import com.czl.module_storehouse.activity.scan.ScanActivity;
import com.czl.module_storehouse.adapter.InventoryScanAdapter;
import com.czl.module_storehouse.bean.EditInventoryInfoBean;
import com.czl.module_storehouse.bean.InventoryProductShiftBean;
import com.czl.module_storehouse.databinding.ActivityInventoryScanBinding;
import com.czl.module_storehouse.event.InventoryScanEvent;
import com.czl.module_storehouse.event.PanSurplusEvent;
import com.czl.module_storehouse.event.ProductBeanEvent;
import com.czl.module_storehouse.event.SortEvent;
import com.czl.module_storehouse.mvp.presenter.InventoryPresenter;
import com.czl.module_storehouse.mvp.presenter.ProductPresenter;
import com.czl.module_storehouse.mvp.view.InventoryView;
import com.czl.module_storehouse.mvp.view.ProductView;
import com.czl.module_storehouse.utils.QrCodeRuleUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * @author xubin
 */
public class InventoryScanActivity extends BaseActivity<ActivityInventoryScanBinding> implements InventoryView, ProductView {

    private InventoryScanAdapter mAdapter;
    private SortBean mSortBean;
    private int mPosition;
    private ProductBean mProductBean;
    private int mInventoryId;
    private boolean mIsPostBackData;

    @InjectPresenter
    InventoryPresenter mPresenter;

    @InjectPresenter
    ProductPresenter mProductPresenter;

    @Override
    protected ActivityInventoryScanBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityInventoryScanBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mToolBinding.toolbarContentTitle.setText("扫码盘点");
        //扫码
        binding.clHeader.textScan.setOnClickListener(v -> goScanActivity());
        binding.btnProfit.setOnClickListener(v -> startPanSurplus());
        binding.btnSubmit.setOnClickListener(v -> submit());
        mAdapter = new InventoryScanAdapter(R.layout.item_inventory_scan, new ArrayList<>());
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            mProductBean = mAdapter.getData().get(position);
            mPosition = position;
            if (view.getId() == R.id.iv_menu) {
                //菜单
                showMenu(mProductBean, view);
            }
        });
        binding.recyclerView.setAdapter(mAdapter);
        EventBus.getDefault().register(this);
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(SortEvent event) {
        if (event != null) {
            SortBean sortBean = event.getSortBean();
            mInventoryId = event.getInventoryId();

            mSortBean = ParcelHelper.copy(sortBean);
            String text;
            if (mSortBean.getProductList() == null) {
                text = mSortBean.getSortName() + "(0)";
            } else {
                text = mSortBean.getSortName() + "(" + mSortBean.getProductList().size() + ")";
            }
            binding.clHeader.tvTitle.setText(text);
            String locationName = mSortBean.getStorehouseLocatName() == null
                    ? SpHelper.INSTANCE.decodeString(Constants.SpKey.STOREHOUSE_LOCATION_NAME)
                    : mSortBean.getStorehouseLocatName();

            binding.clHeader.tvLocName.setText("位置：" + locationName);
            mAdapter.setSortName(mSortBean.getSortName());
            mAdapter.setStorehouseLocatName(locationName);
            mAdapter.addData(mSortBean.getProductList());
            setResultProduct();
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(ProductBeanEvent event) {
        List<ProductBean> productBeans = event.getProductBeanList();
        if (mAdapter != null) {
            if (productBeans != null) {
                for (ProductBean bean : productBeans) {
                    bean.setInventoryResult(ProductBean.TYPE_PANYING);
                }
                mAdapter.addData(productBeans);
            }
            //盘盈
            mIsPostBackData = true;
            setResultProduct();
        }
    }

    private void setResultProduct() {
        int inventoryNum = ProductBean.Companion.getInventoryNum(mAdapter.getData());
        binding.clHeader.tvGoods.setText(getString(R.string.inventory_result_num, inventoryNum));
    }

    /**
     * 扫码单品
     *
     * @param productCode 物品编码
     */
    private void setResultDataByCode(String productCode) {
        if (mSortBean == null) {
            return;
        }
        mPosition = getProductBeanPosCode(productCode, mAdapter.getData());
        if (mPosition >= 0 && mProductBean != null) {
            //扫码盘点单品
            Integer inventoryResult = mProductBean.getInventoryResult();
            if (inventoryResult != null && inventoryResult >= 0) {
                showToast("该物品已盘");
                return;
            }
            mProductBean.setInventoryResult(ProductBean.RESULT_NORMAL);
            productInventory(mProductBean);
        } else {
            //扫码移位
            getProductInfoByCode(productCode);
        }
    }

    /**
     * 扫码单品
     *
     * @param productId 物品id
     */
    private void setResultData(int productId) {
        if (mSortBean == null) {
            return;
        }
        mPosition = getProductBeanPos(productId, mAdapter.getData());
        if (mPosition >= 0 && mProductBean != null) {
            //扫码盘点单品
            Integer inventoryResult = mProductBean.getInventoryResult();
            if (inventoryResult != null && inventoryResult >= 0) {
                showToast("该物品已盘");
                return;
            }
            mProductBean.setInventoryResult(ProductBean.RESULT_NORMAL);
            productInventory(mProductBean);
        } else {
            //扫码移位
            getProductInfo(productId);
        }
    }

    private void getProductInfo(int productId) {
        if (mProductPresenter != null) {
            mProductPresenter.getProductInfo(productId);
        }
    }

    private void getProductInfoByCode(String productCode) {
        if (mProductPresenter != null) {
            mProductPresenter.getProductInfoByCode(productCode);
        }
    }

    private int getProductBeanPosCode(String productCode, List<ProductBean> list) {
        if (list == null) {
            return -1;
        }
        for (int i = 0; i < list.size(); i++) {
            ProductBean bean = list.get(i);
            if (bean.getProductCode() == null) {
                continue;
            }
            if (bean.getProductCode().equals(productCode)) {
                //正常扫码
//                bean.setInventoryResult(ProductBean.RESULT_NORMAL);
                mProductBean = bean;
                return i;
            }
        }
        return -1;
    }

    private int getProductBeanPos(int productId, List<ProductBean> list) {
        if (list == null) {
            return -1;
        }
        for (int i = 0; i < list.size(); i++) {
            ProductBean bean = list.get(i);
            if (bean.getProductId() == null) {
                continue;
            }
            if (bean.getProductId() == productId) {
                //正常扫码
//                bean.setInventoryResult(ProductBean.RESULT_NORMAL);
                mProductBean = bean;
                return i;
            }
        }
        return -1;
    }

    private void setResultData(ProductBean productBean) {
        if (productBean == null || mSortBean == null) {
            return;
        }
        Integer locatId = productBean.getStorehouseLocatId();
        if (locatId == null || locatId <= 0) {
            showToast("该物品不存在");
            return;
        }
        if (productBean.getStorehouseId() == null) {
            return;
        }
        if (productBean.getStorehouseId() != SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_ID)) {
            showToast("扫码物品不是当前仓库物品");
            return;
        }
        if (productBean.getSortId() == null) {
            return;
        }
        if (!productBean.getSortId().equals(mSortBean.getSortId())) {
            showToast(getString(R.string.Scanned_items_are_not_currently_classified_items));
            return;
        }
        int position = productBean.getProductPosition(mAdapter.getData());
        if (position == -1) {
            //移入该仓位,移位成功
            productBean.setInventoryResult(ProductBean.TYPE_UNKNOWN);
            mAdapter.addData(productBean);
            binding.recyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
            mIsPostBackData = true;
            setResultProduct();
        }

    }

    /**
     * 扫码提交单个物品盘点
     *
     * @param productBean
     */
    private void productInventory(ProductBean productBean) {
        if (mPresenter != null) {
            mPresenter.productInventory(productBean);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_menu_title) {
            //添加说明
            showPopup();
        } else if (id == R.id.text_move_in_loc) {
            //移入位置
            InventoryProductShiftBean shiftBean = new InventoryProductShiftBean();
            if (mPresenter != null) {
                mPresenter.inventoryProductShift(shiftBean);
            }
        } else if (id == R.id.text_pro_delete) {
            //删除
            if (mProductBean != null) {
                mAdapter.remove(mProductBean);
            }
            setResultProduct();
        } else if (id == R.id.text_scan) {
            //扫码
            goScanActivity();
        }
    }

    private void startPanSurplus() {
        //盘盈
        PanSurplusEvent event = new PanSurplusEvent(mSortBean);
        EventBus.getDefault().postSticky(event);
        startActivity(new Intent(getContext(), InventoryProfitActivity.class));
    }

    private void showPopup() {
        if (mProductBean == null) {
            return;
        }
        View contentView = View.inflate(getContext(), R.layout.popup_inventory_desc, null);
        EditText etDesc = contentView.findViewById(R.id.et_desc);
        etDesc.setText(mProductBean.getInventoryComment());
        String text = "盘亏";
        if (mProductBean.getInventoryResult() == null) {
            etDesc.setHint("输入盘亏说明");
        } else {
            text = "盘点说明";
            etDesc.setHint("输入说明");
        }
        int width = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(30);
        PopWindowUtils.getInstance().createPopWindow(getContext(), contentView, width, text);
        PopWindowUtils.getInstance().showBasePopupWindow(binding.getRoot());

        contentView.findViewById(R.id.text_confirm).setOnClickListener(v -> {
            PopWindowUtils.getInstance().dismissPopupWindow();
            if (mProductBean.getInventoryResult() == null) {
                mProductBean.setInventoryResult(ProductBean.RESULT_DEFICIT);
                mAdapter.setData(mPosition, mProductBean);
            }
            mProductBean.setInventoryComment(etDesc.getText().toString());
            productInventory(mProductBean);
        });
    }

    private void showMenu(ProductBean bean, View anchor) {
        PopupWindow window = new PopupWindow(getContext());
        View view;
        if (bean.getInventoryResult() != null && ProductBean.TYPE_UNKNOWN == bean.getInventoryResult()) {
            view = View.inflate(getContext(), R.layout.menu_inventory_scan, null);
            view.findViewById(R.id.text_move_in_loc).setOnClickListener(v -> {
                window.dismiss();
                //移入位置
                InventoryProductShiftBean shiftBean = new InventoryProductShiftBean();
                shiftBean.setProductBean(mProductBean);
                shiftBean.setInventoryId(mInventoryId);
                shiftBean.setShiftLocatIn(mSortBean.getStorehouseLocatId());
                if (mPresenter != null) {
                    mPresenter.inventoryProductShift(shiftBean);
                }
            });
            view.findViewById(R.id.text_pro_delete).setOnClickListener(v -> {
                window.dismiss();
                if (mProductBean != null) {
                    mAdapter.remove(mProductBean);
                }
                setResultProduct();
            });
        } else {
            view = View.inflate(getContext(), R.layout.menu_add_ware_house, null);
            TextView tvTitle = view.findViewById(R.id.tv_menu_title);
            if (bean.getInventoryResult() == null) {
                tvTitle.setText("盘亏");
            } else {
                tvTitle.setText("盘点说明");
            }
            tvTitle.setOnClickListener(v -> {
                window.dismiss();
                showPopup();
            });
        }

        window.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setContentView(view);
        window.setFocusable(true);
        window.setTouchable(true);
        window.setOutsideTouchable(true);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int offsetY = window.getContentView().getMeasuredHeight();
        int[] location = new int[2];
        anchor.getLocationOnScreen(location);
        int x = location[0];
        int top = SizeUtils.dp2px(38);
        binding.btnSubmit.post(() -> {
            int height = binding.btnSubmit.getHeight();
            if (offsetY + x > ScreenUtils.getScreenHeight() - top - height) {
                PopupWindowCompat.showAsDropDown(window, anchor, 0, -offsetY, Gravity.END);
            } else {
                PopupWindowCompat.showAsDropDown(window, anchor, 0, 0, Gravity.END);
            }
        });
    }

    protected final ActivityResultLauncher<Intent> mLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getData() != null) {
                    String productResult = QrCodeRuleUtils.handleStorehouseProductResult(result.getData().getStringExtra(ScanActivity.RESULT));
                    setResultDataByCode(productResult);
                }
            });

    protected void goScanActivity() {
        mLauncher.launch(new Intent(getContext(), ScanActivity.class));
    }

    public void submit() {
        EditInventoryInfoBean infoBean = new EditInventoryInfoBean();
        List<LocatListBean> listBeans = new ArrayList<>();
        LocatListBean listBean = new LocatListBean();
        listBeans.add(listBean);
        infoBean.setLocatList(listBeans);
        List<SortBean> sortBeans = new ArrayList<>();
        listBean.setSortList(sortBeans);
        infoBean.setInventoryId(mInventoryId);
        infoBean.setStatus(2);
        if (mSortBean != null) {
            mSortBean.setProductList(mAdapter.getData());
            if (mSortBean.getStorehouseLocatId() != null) {
                listBean.setStorehouseLocatId(mSortBean.getStorehouseLocatId());
            }
            sortBeans.add(mSortBean);
        }
        if (mPresenter != null) {
            mPresenter.editInventoryInfo(infoBean);
        }
    }

    protected void back() {
        if (mIsPostBackData) {
            EventBus.getDefault().postSticky(new InventoryScanEvent(mSortBean));
        }
        finish();
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (ProductPresenter.TAG_PRODUCT_INFO_BY_CODE.equals(httpResponse.getRequestTag())) {
            //扫码移位
            ProductBean productBean = (ProductBean) httpResponse.getData();
            setResultData(productBean);
        } else if (InventoryPresenter.TAG_INVENTORY_SHIFT.equals(httpResponse.getRequestTag())) {
            //移入该仓位,移入成功
            mProductBean.setInventoryResult(ProductBean.RESULT_NORMAL);
            mAdapter.setViewData(mPosition, "shift");

        } else if (InventoryPresenter.TAG_INVENTORY_PRODUCT.equals(httpResponse.getRequestTag())) {
            //提交扫码正常盘点，盘点说明，盘亏操作
            mAdapter.setViewData(mPosition, "operation");
            binding.recyclerView.scrollToPosition(mPosition);
            mIsPostBackData = true;
            setResultProduct();
        } else if (InventoryPresenter.TAG_INVENTORY_EDIT_INFO.equals(httpResponse.getRequestTag())) {
            showToast("提交成功");
            back();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
